package cgs_worksheet

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/base"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"net/http"
)

func init() {
	server.Get("/api/v1/app/get", getApp, "获取应用信息", server.None)
	server.Post("/api/v1/worksheet/getWorksheetInfo", getWsInfo, "获取工作表结构信息", server.None)
	server.Post("/api/v1/worksheet/getFilterRows", getFilterRows, "获取列表", server.None)
	server.Post("/api/v1/worksheet/addRow", addRow, "新建行记录", server.None)
	server.Get("/api/v1/worksheet/getRowById", getRowById, "获取行记录详情", server.None)
	server.Post("/api/v1/worksheet/deleteRow", deleteRow, "删除行记录", server.None)
	server.Post("/api/v1/worksheet/editRow", editRow, "更新行记录详情", server.None)
	server.Post("/api/v1/worksheet/addRows", addRows, "批量新建行记录", server.None)
	server.Post("/api/v1/worksheet/editRows", editRows, "批量编辑行记录", server.None)
	server.Post("/api/v1/worksheet/clear", clearWorksheet, "清空表单数据", server.None)
}

func clearWorksheet(w http.ResponseWriter, r *http.Request) {
	param := struct {
		WorksheetId primitive.ObjectID	`json:"worksheetId"`
	}{}
	_ = helper.ReadRequestBody(&param, w, r)
	if param.WorksheetId.IsZero() {
		_, _ = helper.WriteJSON(w, server.Fail("参数缺少"))
		return
	}

	user, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	wsService := NewWorksheetService()
	err = wsService.ClearWorksheet(param.WorksheetId, user)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Clear successfully!"))
}

func getApp(w http.ResponseWriter, r *http.Request) {
	// appKey,sign
	visualId := r.FormValue("visualId")
	if visualId == "" {
		_, _ = helper.WriteJSON(w, server.Fail("参数缺少"))
		return
	}

	wsInfo := &WorksheetInfo{
		VisualId: visualId,
	}
	duModel := base.GenerateDataUserModel(wsInfo, r)
	wsService := NewWorksheetService()
	result, err := wsService.ListAppWorksheet(duModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK().WithData(result))
}

func getWsInfo(w http.ResponseWriter, r *http.Request) {
	// appKey, sign, worksheetId
	param := struct {
		WorksheetId primitive.ObjectID	`json:"worksheetId"`
	}{}
	_ = helper.ReadRequestBody(&param, w, r)
	if param.WorksheetId.IsZero() {
		_, _ = helper.WriteJSON(w, server.Fail("参数缺少"))
		return
	}

	wsInfo := &WorksheetInfo{
		Id: param.WorksheetId,
	}

	duModel := base.GenerateDataUserModel(wsInfo, r)
	wsService := NewWorksheetService()
	result, err := wsService.GetOne(duModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK().WithData(result))
}

func getFilterRows(w http.ResponseWriter, r *http.Request) {
	// appKey, sign, worksheetId (id), pageSize, pageNo,
	filterParam := FilterParam{}
	err := helper.ReadRequestBody(&filterParam, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	validator := helper.GetValidator()
	err = validator.Struct(filterParam)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail("参数缺少"))
		return
	}

	duModel := base.GenerateDataUserModel(&filterParam, r)
	wsService := NewWorksheetService()
	result, err := wsService.GetFilterRows(duModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, result)

}

func addRow(w http.ResponseWriter, r *http.Request) {
	if !hasWriteAuthority(r) {
		_, _ = helper.WriteJSON(w, server.Fail("Permission denied."))
		return
	}

	// appKey, sign, worksheetId, data
	wsRowDataVo := &WsRowDataVo{}
	err := helper.ReadRequestBody(wsRowDataVo, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	validator := helper.GetValidator()
	err = validator.Struct(wsRowDataVo)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail("参数缺少"))
		return
	}

	dataUserModel := base.GenerateDataUserModel(&wsRowDataVo.WsRowData, r)
	wsService := NewWorksheetService()
	err = wsService.AddRow(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Add successfully!").WithData(bson.M{
		"rowId": wsRowDataVo.RowId,
	}))
}

func getRowById(w http.ResponseWriter, r *http.Request) {
	worksheetId, err := primitive.ObjectIDFromHex(r.FormValue("worksheetId"))
	//rowId, err2 := primitive.ObjectIDFromHex(r.FormValue("rowId"))
	rowId := r.FormValue("rowId")
	if err != nil || rowId == "" {
		_, _ = helper.WriteJSON(w, server.Fail("参数缺少"))
		return
	}

	wsRowData := &WsRowData{
		RowId:       rowId,
		WorksheetId: worksheetId,
	}
	//wsRowData.AppKey = appKey
	//wsRowData.Sign = sign

	dataUserModel := base.GenerateDataUserModel(wsRowData, r)
	wsService := NewWorksheetService()
	result, err := wsService.GetRowById(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	if result == nil {
		_, _ = helper.WriteJSON(w, server.Fail("Not found.'"))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Get successfully!").WithData(result))
}

func deleteRow(w http.ResponseWriter, r *http.Request) {
	if !hasWriteAuthority(r) {
		_, _ = helper.WriteJSON(w, server.Fail("Permission denied."))
		return
	}
	// appKey, sign, worksheetId, rowId
	wsRowDataVo := &WsRowDataVo{}
	err := helper.ReadRequestBody(wsRowDataVo, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	validator := helper.GetValidator()
	err = validator.Struct(wsRowDataVo)
	if err != nil || wsRowDataVo.RowId == "" {
		_, _ = helper.WriteJSON(w, server.Fail("参数缺少"))
		return
	}

	dataUserModel := base.GenerateDataUserModel(&wsRowDataVo.WsRowData, r)
	wsService := NewWorksheetService()
	err = wsService.DeleteRowLogic(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Delete successfully!"))
}

func editRow(w http.ResponseWriter, r *http.Request) {
	if !hasWriteAuthority(r) {
		_, _ = helper.WriteJSON(w, server.Fail("Permission denied."))
		return
	}
	// appKey, sign, rowId, data
	wsRowDataVo := &WsRowDataVo{}
	err := helper.ReadRequestBody(wsRowDataVo, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail("参数缺少"))
		return
	}

	validator := helper.GetValidator()
	err = validator.Struct(wsRowDataVo)
	if err != nil || wsRowDataVo.RowId == "" {
		_, _ = helper.WriteJSON(w, server.Fail("参数缺少"))
		return
	}
	if len(wsRowDataVo.Data) == 0 {
		_, _ = helper.WriteJSON(w, server.Fail("数据不能为空"))
		return
	}

	dataUserModel := base.GenerateDataUserModel(&wsRowDataVo.WsRowData, r)
	wsService := NewWorksheetService()
	err = wsService.UpdateRow(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Update successfully!"))
}

func editRows(w http.ResponseWriter, r *http.Request) {
	if !hasWriteAuthority(r) {
		_, _ = helper.WriteJSON(w, server.Fail("Permission denied."))
		return
	}
	// appKey, sign, rowId, data
	wsRowDataBatch := &WsRowDataBatch{}
	err := helper.ReadRequestBody(wsRowDataBatch, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail("参数缺少"))
		return
	}

	validator := helper.GetValidator()
	err = validator.Struct(wsRowDataBatch)
	if err != nil || len(wsRowDataBatch.RowIds) == 0 {
		_, _ = helper.WriteJSON(w, server.Fail("参数缺少"))
		return
	}
	if len(wsRowDataBatch.Data) == 0 {
		_, _ = helper.WriteJSON(w, server.Fail("数据不能为空"))
		return
	}

	dataUserModel := base.GenerateDataUserModel(wsRowDataBatch, r)
	wsService := NewWorksheetService()
	err = wsService.UpdateRowBatch(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Update successfully!"))
}

func addRows(w http.ResponseWriter, r *http.Request) {
	if !hasWriteAuthority(r) {
		_, _ = helper.WriteJSON(w, server.Fail("Permission denied."))
		return
	}
	// appKey, sign, worksheetId, rows []
	rowDataVo := &BatchAddRowVo{}
	err := helper.ReadRequestBody(rowDataVo, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	validator := helper.GetValidator()
	err = validator.Struct(rowDataVo)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail("参数缺少"))
		return
	}
	if len(rowDataVo.Rows) == 0 {
		_, _ = helper.WriteJSON(w, server.Fail("数据不能为空"))
		return
	}
	dataUserModel := base.GenerateDataUserModel(rowDataVo, r)
	wsService := NewWorksheetService()
	err = wsService.BatchAddRow(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Add successfully!"))
}

func hasWriteAuthority(r *http.Request) bool {
	v := r.Context().Value("authType")
	if v == nil {
		return false
	}
	return v.(string) == "2"
}
